package jvs.vfs.resource;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import jvs.vfs.IFileBaseImpl;

/**
 * @author qiangli
 *
 */
public class ResourceFileImpl extends IFileBaseImpl {
	private String path = null;
	public ResourceFileImpl(URI uri) {
		super(uri);
		//
		path = uri.getPath();
		//remove anything after ! which by convention, should be part of another resource (e.g in a jar)
		int idx = path.indexOf("!");
		if (idx > 0) {
			path = path.substring(0,idx);
		}
	}

	public boolean create() {
		return false;
	}

	public boolean delete() {
		return false;
	}

	private String getPath() {
		return path;
	}
	
	public boolean exists() {
		return true;
	}

	public InputStream getInputStream() {
		try {
			String p = getPath();
			return getClass().getResourceAsStream(p);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	
	public OutputStream getOutputStream() {
		
		return null;
	}

	
	public boolean isDirectory() {
		return getPath().endsWith("/");
	}

	private String[] list = null;
	
	synchronized public String[] list() {
		if (list == null) {
			List<String> l = new ArrayList<String>();
			try {
				String p = getPath();
				BufferedReader in = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(p+"index.txt")));
				String str;
				while ((str = in.readLine()) != null) {
					str = str.trim();
					if (str.length() > 0) {
						l.add(str);
					}
				}
				in.close();
	
			} catch (Exception e) {
				//e.printStackTrace();
			}
			list = (String[])l.toArray(new String[0]);
		}
		return list;
	}

	public boolean mkdir() {
		return false;
	}


	public boolean move(URI uri) {
		return false;
	}

}
